package leetcode;

class MyLinkedList {
    int size;
    ListNode dummy;
    public MyLinkedList() {
        size = 0;
        dummy=new ListNode();
    }
    
    public int get(int index) {
        if (index < 0 || index > (size-1)) {
            return -1;
        }
        ListNode cur=dummy;
        while (index!=0) {
            cur=cur.next;
            index--;
        }
        return cur.next.val ;
    }
    
    public void addAtHead(int val) {
        ListNode node=new ListNode(val);
        node.next=dummy.next;
        dummy.next=node;
        size++;
    }
    
    public void addAtTail(int val) {
        ListNode cur=dummy;
        ListNode node=new ListNode(val);
        while (cur.next!=null) {
            cur=cur.next;
        }
        cur.next=node;
        size++;
    }
    
    public void addAtIndex(int index, int val) {
        if (index < 0 || index > size) {
            return;
        }
        if(index==size){
            addAtTail(val);
        }else{
            ListNode cur=dummy;
            ListNode node=new ListNode(val);

            while (index!=0) {
                cur=cur.next;
                index--;
            }
            node.next=cur.next;
            cur.next=node;
            size++;
        }

    }
    
    public void deleteAtIndex(int index) {
        if (index < 0 || index > (size-1)) {
            return;
        }
        int m=index;
        ListNode cur=dummy;


        while (index!=0) {
            cur=cur.next;
            index--;
        }

        if(m ==(size-1)){
            cur.next=null;
        }else{
            cur.next=cur.next.next;
        }
        size--;
    }
}

/**
 * Your MyLinkedList object will be instantiated and called as such:
 * MyLinkedList obj = new MyLinkedList();
 * int param_1 = obj.get(index);
 * obj.addAtHead(val);
 * obj.addAtTail(val);
 * obj.addAtIndex(index,val);
 * obj.deleteAtIndex(index);
 */